/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年10月5日 上午11:04:18
 */
package com.absir.appserv.system.service;

import java.net.URLEncoder;

import com.absir.appserv.configure.JConfigureUtils;
import com.absir.appserv.system.bean.proxy.JiUserBase;
import com.absir.appserv.system.configure.JHuaweiConfigure;
import com.absir.appserv.system.helper.HelperClient;
import com.absir.bean.inject.value.Bean;
import com.absir.core.kernel.KernelCharset;
import com.absir.core.kernel.KernelString;

/**
 * @author absir
 *
 */
@Bean
public class HuaweiService implements IdentityService {

	/** HUAWEI_CONFIGURE */
	public static final JHuaweiConfigure HUAWEI_CONFIGURE = JConfigureUtils.getConfigure(JHuaweiConfigure.class);

	/** PLAT_FORM_NAME */
	public static final String PLAT_FORM_NAME = "Huawei";

	// 验证accessToken地址
	public static final String VALID_TOKEN_ADDR = "https://api.vmall.com/rest.php";

	public static class UserInfo {

		public String userID;

		public String userName;

		public String languageCode;

		public int userState;

		public int userValidStatus;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.appserv.system.service.IdentityService#getUserBase(java.lang
	 * .String[])
	 */
	@Override
	public JiUserBase getUserBase(String[] parameters) {
		if (parameters.length == 2) {
			String accessToken = parameters[1];
			// https请求
			String postBody = "nsp_svc=OpenUP.User.getInfo&nsp_ts=";
			postBody += String.valueOf(System.currentTimeMillis() / 1000);
			try {
				postBody += "&access_token=" + URLEncoder.encode(accessToken, "utf-8");

			} catch (Exception e) {
				return null;
			}

			UserInfo userInfo = HelperClient.openConnection(VALID_TOKEN_ADDR, true, postBody.getBytes(KernelCharset.UTF8),
					UserInfo.class);
			if (userInfo != null && !KernelString.isEmpty(userInfo.userID)) {
				return SecurityService.ME.openUserBase(userInfo.userID, null, PLAT_FORM_NAME);
			}
		}

		return null;
	}
}
